package com.fivestyle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fivestyle.common.result.R;
import com.fivestyle.entity.Collection;
import com.fivestyle.entity.vo.BookVo;
import com.fivestyle.mapper.CollectionMapper;
import com.fivestyle.service.BookService;
import com.fivestyle.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张代钊
 * @since 2021-08-04
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {

    @Autowired
    private BookService bookService;

    @Override
    public R maxCollectBook(Long current, Long size) {

        List<BookVo> bookList = baseMapper.maxCollectBook(current,size);

        return R.ok().data("bookList",bookList).data("total",bookService.bookTotal());
    }

    @Transactional
    @Override
    public R collectOrNot(String userId, String bookId) {
        Collection one = baseMapper.selectOne(new QueryWrapper<Collection>().eq("book_id", bookId).eq("user_id", userId));
        try {
            if( one != null){
                baseMapper.deleteById(one);
                return R.ok().message("取消收藏成功！");
            }else {
                Collection collection = new Collection();
                collection.setBookId(bookId);
                collection.setUserId(userId);
                baseMapper.insert(collection);
                return R.ok().message("收藏该图书成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return R.error().message("图书的收藏或者取消收藏的接口，发生了报错！");
        }
    }
}
